import Koa from "koa"
import Router from "koa-router"
import bodyparser from "koa-bodyparser"
import cors from "@koa/cors"
import { Op as op, Sequelize, DataTypes, where} from "sequelize"

let port = 5000

let app = new Koa()
let router = new Router()
app.use(bodyparser())
app.use(cors())
const sequelize = new Sequelize("demo", "root", "123456", {
    dialect: "mysql"
})
let Book = sequelize.define("book", {
    bookName: {
        type: DataTypes.STRING
    },
    author: {
        type: DataTypes.STRING
    }
})
// sequelize.sync({ force: true })
router.get("/book", async (ctx) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body
    let keyWord = ctx.request.query.keyWord || ""
    let res

    if (keyWord) {
        res = await Book.findAll({
            where: {
                [op.or]: {
                    bookName: {
                        [op.like]: `%${keyWord}%`
                    },
                    author: {
                        [op.like]: `%${keyWord}%`
                    },
                }
            }
        })
    } else {
        res = await Book.findAll()
    }
    ctx.body = {
        code: 1000,
        msg: "成功",
        data: res
    }
})
router.get("/book/:id", async (ctx) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body
    let keyWord = ctx.request.query.keyWord || ""
    let books = await Book.findByPk(id)
    ctx.body = {
        code: 1000,
        msg: "成功",
        data: books
    }
})
router.post("/book", async (ctx) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body
    let keyWord = ctx.request.query.keyWord || ""
    let books = await Book.create(obj)
    ctx.body = {
        code: 1000,
        msg: "成功",
        data: books
    }
})
router.put("/book/:id", async (ctx) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body
    let keyWord = ctx.request.query.keyWord || ""
    let books = await Book.update(obj,{Where:{id:id}})
    ctx.body = {
        code: 1000,
        msg: "成功",
        data: books
    }
})
router.delete("/book/:id", async (ctx) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body
    let keyWord = ctx.request.query.keyWord || ""
    let book= await Book.destroy({where:{id:id}})
    ctx.body =  ctx.body = {
        code: 1000,
        msg: "成功",
        data: book
    }
})
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(port, function () {
    console.log(`服务运行于： http://localhost:${port}`);
})